//
//  MeUserInfoViewController.m
//  HTHappySale
//
//  Created by 创维海通 on 2017/9/20.
//  Copyright © 2017年 zxyywy. All rights reserved.
//

#import "MeUserInfoViewController.h"
#import "MainViewController.h"
#import "RegionViewController.h"
#import "NickViewController.h"

#import "MyCodeViewController.h"
#import "UpdateTelViewController.h"
#import "CodeScanViewController.h"
#import "MyCodeViewController.h"

//Request
#import "HTTPPromise+Login.h"
#import "HTTPPromise+Me.h"

//Model
#import "UserInfoModel.h"
//Model
#import "WXAuth2Model.h"

//Cell
#import "PortraitCell.h"
#import "MeUserCustomCell.h"

//Tools
#import "HTPhotoManager.h"
#import "AppUtil.h"

@interface MeUserInfoViewController ()<UITableViewDelegate,UITableViewDataSource,RegionCodeParamsDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
     int areaCode;               //区域代码
}
@property (strong, nonatomic) IBOutlet UITableView *MeUserInfoTableView;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *infoBottomConstraint;
@property (nonatomic,strong) UserInfoModel *userInfoModel;
@property (strong, nonatomic) IBOutlet UILabel *RoleLabel;

@property (strong, nonatomic) Region2Model *model;

@end

@implementation MeUserInfoViewController
#pragma mark -init
#define PortraitIdentifyCell @"PortraitCell"
#define MeUserCustomIdentifyCell @"MeUserCustomCell"

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //Xib
    UINib *nib = [UINib nibWithNibName:NSStringFromClass([PortraitCell class])
                                bundle:[NSBundle mainBundle]];
    [_MeUserInfoTableView registerNib:nib forCellReuseIdentifier:PortraitIdentifyCell];
    
    UINib *nib1 = [UINib nibWithNibName:NSStringFromClass([MeUserCustomCell class])
                                bundle:[NSBundle mainBundle]];
    [_MeUserInfoTableView registerNib:nib1 forCellReuseIdentifier:MeUserCustomIdentifyCell];
    
    [self initTableView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addNavigationLeftView:@"" andType:0];
    [self addNavigationMiddleView:@"个人信息"];
    
    MainViewController *mainCtrol = (MainViewController *)self.tabBarController;
    [mainCtrol hiddenTabBar];
    
    [self initRequest];
}

- (void)initRequest
{
    NSDictionary *meUserParam = @{};
    NSData *jsonData;
    
    if ([NSJSONSerialization isValidJSONObject:meUserParam])
    {
        NSError *error;
        jsonData = [NSJSONSerialization dataWithJSONObject:meUserParam options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }
    __weak __typeof(self)weakSelf = self;
    [HTTPPromise requestUserInfoParams:jsonData Success:^(id responseObj) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"%@",responseObj);
        int successRet =[responseObj[@"ret"] intValue];
        //(数据转模型）
        if (successRet == 0) {
            strongSelf.userInfoModel = [[UserInfoModel alloc] init];
            [strongSelf.userInfoModel setValuesForKeysWithDictionary:responseObj[@"info"]];
            NSLog(@"signKey :%@",strongSelf.userInfoModel.mobile);
            
            strongSelf.model = [[Region2Model alloc] init];
            [strongSelf.model setRId:[NSString stringWithFormat:@"%d",strongSelf.userInfoModel.region]];
            [strongSelf.model setName:strongSelf.userInfoModel.regionName];
            
            HTCFUDFCache(kRoleKey, [NSNumber numberWithInt:_userInfoModel.role]);
            roleType = [HTCFUDFGetValue(kRoleKey) intValue];
            NSLog(@"%@",strongSelf.model.rId);
            [strongSelf.MeUserInfoTableView reloadData];
        }else{
            [AppUtil showTipMessage:responseObj[@"desc"]];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error.userInfo);
    }];
}

- (void)initTableView
{
    _MeUserInfoTableView.tableFooterView = [[UIView alloc] init];
}

#pragma mark -tableDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_userInfoModel != nil) {
        if ((int)_userInfoModel.role == 2 || (int)_userInfoModel.role == 3)
        {
            return 7;
        }
        return 6;
    }
    return 0;
}

#define cellIdentify @"cell"
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0){
        PortraitCell *portraitCell = [tableView dequeueReusableCellWithIdentifier:PortraitIdentifyCell];
        [portraitCell configureCell:_userInfoModel];
        portraitCell.selectionStyle = UITableViewCellSelectionStyleNone;
        portraitCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        return portraitCell;
    }else{
        MeUserCustomCell *meUserCustomCell = [tableView dequeueReusableCellWithIdentifier:MeUserCustomIdentifyCell];
        [meUserCustomCell configureCell:_userInfoModel withRole:(int)_userInfoModel.role withAtIndex:indexPath.row];
        meUserCustomCell.selectionStyle = UITableViewCellSelectionStyleNone;
        if(indexPath.row != 3){
            if (indexPath.row == 5) {
                if(_userInfoModel.role != 0)
                {
                    meUserCustomCell.accessoryType = UITableViewCellAccessoryNone;
                    
                }
            }else if (indexPath.row == 6)
            {
                if (_userInfoModel.role == 2) {
                    UIImageView *scanImg = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 30, 12, 20, 20)];
                    scanImg.image = HTCFQuickImage(@"2Code");
                    scanImg.backgroundColor = [UIColor yellowColor];
                    [meUserCustomCell addSubview:scanImg];
                    meUserCustomCell.accessoryType = UITableViewCellAccessoryNone;
                }else if (_userInfoModel.role == 3)
                {
                    meUserCustomCell.accessoryType = UITableViewCellAccessoryNone;
                }
            }
            else{
                meUserCustomCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
        }
        
        return meUserCustomCell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0){
        return 60;
    }
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
    {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                 delegate:self
                                                        cancelButtonTitle:@"取消"
                                                   destructiveButtonTitle:nil
                                                        otherButtonTitles:@"拍照", @"从手机相册选择", nil];
        [actionSheet showInView:self.view];
    }else if (indexPath.row == 1)
    {
        NickViewController *nickVC = [[NickViewController alloc] init:_userInfoModel.nickname];
        [self.navigationController pushViewController:nickVC animated:YES];
    }else if (indexPath.row == 2)
    {
        RegionViewController *regionVC = [[RegionViewController alloc] init];
        regionVC.citydelegate = self;
        if(_model != nil)
        {
            [regionVC setValue:_model forKey:@"paramModel"];
        }
        
        [self.navigationController pushViewController:regionVC animated:YES];
    }else if (indexPath.row == 3)
    {
        
    }else if (indexPath.row == 4)
    {
        UpdateTelViewController *updateTelVC = [[UpdateTelViewController alloc] init];
        [self.navigationController pushViewController:updateTelVC animated:YES];
    }else if (indexPath.row == 5)
    {
        if (_userInfoModel.role == 0) {
            CodeScanViewController *CodeScanVC = [[CodeScanViewController alloc] init];
            [self.navigationController pushViewController:CodeScanVC animated:YES];
        }
    }else if (indexPath.row == 6)
    {
        if (_userInfoModel.role == 2) {
            MyCodeViewController *myCodeVC = [[MyCodeViewController alloc] init];
            [self.navigationController pushViewController:myCodeVC animated:YES];
        }else if (_userInfoModel.role == 3)
        {
            
        }
    }
}

#pragma mark -RegionCodeParamsDelegate
- (void)transmitCity:(Region2Model *)model
{
    NSLog(@"model:%@",model.rId);
    areaCode = [model.rId intValue];
    UITextField *tempText = [_MeUserInfoTableView viewWithTag:102];
    tempText.text = model.name;
    
    _model = [[Region2Model alloc] init];
    _model = model;
}

#pragma mark UIActionSheetDelegate Call Back Implementation

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (0 == buttonIndex)
    {
        // 开始拍照
        [self takePhoto];
    }
    else if(1 == buttonIndex)
    {
        //打开本地相册
        [self localPhoto];
    }
}

#pragma mark -Action
// 开始拍照
-(void)takePhoto
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        //先检查相机可用是否
        BOOL cameraIsAvailable = HTCFAppCanAccessCamera;
        if (YES == cameraIsAvailable) {
            [self presentViewController:picker animated:YES completion:nil];
        }else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请在iPhone的“设置-隐私-相机”选项中，允许本应用程序访问你的相机。" delegate:self cancelButtonTitle:@"好，我知道了" otherButtonTitles:nil];
            [alert show];
        }
        
    }
}

// 打开本地相册
-(void)localPhoto
{
    if(HTCFAppCanAccessPhotoLibrary){
        //本地相册不需要检查，因为UIImagePickerController会自动检查并提醒
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.delegate = self;
        //设置选择后的图片可被编辑
        picker.allowsEditing = YES;
        [self presentViewController:picker animated:YES completion:nil];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请在iPhone选项中，允许本应用程序访问你的相册。" delegate:self cancelButtonTitle:@"好，我知道了" otherButtonTitles:nil];
        [alert show];
    }
}

#pragma mark UIImagePickerControllerDelegate Call Back Implementation
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    NSLog(@"%@",type);
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        NSString *key = nil;
        NSLog(@"%d",picker.allowsEditing);
        if (picker.allowsEditing)
        {
            key = UIImagePickerControllerEditedImage;
        }
        else
        {
            key = UIImagePickerControllerOriginalImage;
        }
        //获取图片
        UIImage *image = [info objectForKey:key];
        
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera || picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
            //压缩图片质量
            image = [[HTPhotoManager sharedTool] reduceImage:image percent:0.1];
            CGSize imageSize = image.size;
            imageSize.height = 240;
            imageSize.width = 240;
            //压缩图片尺寸
            image = [[HTPhotoManager sharedTool] imageWithImageSimple:image scaledToSize:imageSize];
            
            NSString *filePath = HTCFAppCacheDirectory;
            NSString *filePath2 = [NSString stringWithFormat:@"%@%@",filePath,@"/MyImage/pic.png"];
            NSString *filePath3 = [NSString stringWithFormat:@"%@%@",filePath,@"/MyImage"];
            
            if(HTCFFileIsExist(filePath2)){
//                HTCFFileDeleteFile(filePath2);
                
                [self saveLoclhost:image AtWithFile:filePath2];
            }else{
                //创建目录
                if(HTCFFileDirectoryCreate(filePath3))
                {
                    [self saveLoclhost:image AtWithFile:filePath2];
                }
            }
        NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
//        NSLog(@"%@",imgData);
        NSString *encodedImageStr = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        //上传到服务器
        [self doAddPhoto:encodedImageStr];
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:^{
            [_MeUserInfoTableView reloadData];
        }];
      }
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        [_MeUserInfoTableView reloadData];
    }];
}

- (void)doAddPhoto:(NSString *)imgBase64Str{
    NSDictionary *meUserParam = @{@"type":@"png",@"image":imgBase64Str};
    NSData *jsonData;
    
    if ([NSJSONSerialization isValidJSONObject:meUserParam])
    {
        NSError *error;
        jsonData = [NSJSONSerialization dataWithJSONObject:meUserParam options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }
//    __weak __typeof(self)weakSelf = self;
    [HTTPPromise requestUserPortraitParams:jsonData Success:^(id responseObj) {
        NSLog(@"%@",responseObj);
        int successRet =[responseObj[@"ret"] intValue];
        //(数据转模型）
        if (successRet == 0) {
            [AppUtil showTipMessage:responseObj[@"desc"]];
        }else{
            [AppUtil showTipMessage:responseObj[@"desc"]];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error.userInfo);
    }];
}

- (void)saveLoclhost:(UIImage *)image AtWithFile:(NSString *)filePath{
    BOOL success = [UIImagePNGRepresentation(image) writeToFile:filePath  atomically:YES];
    if (success){
        NSLog(@"写入本地成功");
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
